﻿
using Services.Activity.Infrastructure;

namespace Services.Activity.WebApi.Services;

public class ActivityServices(IServiceScopeFactory serviceScopeFactory) : BackgroundService
{
    private readonly ActivityDbContext activityDbContext = serviceScopeFactory.CreateScope().ServiceProvider.GetRequiredService<ActivityDbContext>();
    protected async override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (true)
        {
            //每30秒查询一遍数据库看一下是不是有已经完成的活动
            var activities = this.activityDbContext.Activities.Where(x => x.ActivityCompleteTime < DateTime.Now && !x.ActivityComplete).ToList();
            if (activities.Count != 0)
            {
                activities.ForEach(x =>
                {
                    x.SetActivityComplete();
                });
                await this.activityDbContext.SaveChangesAsync(stoppingToken);
            }
            await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
        }
    }
}
